package com.simtop.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.LogInfo;
import com.simtop.pojo.User;
import com.simtop.service.LogInfoService;
import com.simtop.util.ExcelUtils;
import com.simtop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author lvyongwei
 */
@CrossOrigin
@Controller
@RequestMapping("/logInfo")
public class LogInfoController {

    @Autowired
    private LogInfoService logInfoService;

    @Autowired
    private ExcelUtils excelUtils;

    /**
     * 获取所有日志信息
     * @param data
     * @return
     */
    @PostMapping("/getAllLogInfo")
    @ResponseBody
    public ServerResponse<Object> getAllLogInfo(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        if(!u.getRoleId().equals(1)){
            return ServerResponse.createByErrorMsg("无权限查看日志");
        }
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum = 1;
        }
        if(ObjectUtils.isEmpty(pageSize)){
            pageSize = 10;
        }
        PageHelper.startPage(pageNum,pageSize);
        List<LogInfo> logInfos = logInfoService.getAllLogInfo(null);
        PageInfo<LogInfo> pageInfo = new PageInfo<LogInfo>(logInfos);
        return ServerResponse.createBySuccess("获取日志成功",pageInfo);
    }


    /**
     * 下载日志
     * @param request
     * @param response
     */
    @GetMapping("/downloadLog")
    public void downloadLog(HttpServletRequest request, HttpServletResponse response){
        List<LogInfo> logInfos = logInfoService.getAllLogInfo(null);
        excelUtils.cooperationData(request,response,logInfos,"用户操作日志",LogInfo.class);
    }
}
